<template>
  <div>
    <Category :scene="scene" />
    <el-card class="attr_card">
      <div v-show="scene">
        <el-button
          @click="addAttr"
          type="primary"
          icon="plus"
          :disabled="!categoryStore.c3Id"
        >
          添加平台属性
        </el-button>
        <el-table
          v-loading="loading"
          class="attr_table"
          :border="true"
          :data="attrArrDate"
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            align="center"
            width="250"
          ></el-table-column>
          <el-table-column label="属性值名称" align="center">
            <template #="{ row }">
              <el-tag
                class="attr_table-tag"
                v-for="item in row.attrValueList"
                :key="item.id"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template #="{ row }">
              <el-button
                @click="updateAttr(row)"
                type="primary"
                icon="Edit"
              ></el-button>
              <el-popconfirm
                :title="`你确定删除${row.attrName}?`"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button type="danger" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <template #empty>
            <img
              class="table_emptyImg"
              src="../../../assets/images/Minions.svg"
            />
            <p class="table_emptyP">说了人家没数据呢?</p>
          </template>
        </el-table>
      </div>
      <div v-show="!scene">
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form v-loading="loading" :inline="true">
          <el-form-item label="属性名称">
            <el-input
              v-model="attrParams.attrName"
              placeholder="请你输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          @click="addAttrValue"
          :disabled="attrParams.attrName === ''"
          class="attr_button-marginTop"
          type="primary"
          icon="Plus"
        >
          添加属性
        </el-button>
        <el-button
          class="attr_button-marginTop"
          type="danger"
          icon="Delete"
          @click="cancel"
        >
          取消
        </el-button>
        <el-table
          :data="attrParams.attrValueList"
          class="attr_card"
          :border="true"
        >
          <el-table-column
            type="index"
            label="序号"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => inputArr[$index] = vc"
                @blur="toLook(row, $index)"
                v-if="row.flag"
                v-model="row.valueName"
                placeholder="请你输入属性值名称"
              ></el-input>
              <div @click="toEdit(row, $index)" v-else>{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ $index }">
              <el-button
                @click="attrParams.attrValueList.splice($index, 1)"
                type="danger"
                icon="Delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >
          保存
        </el-button>
        <el-button type="danger" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue";
// 引入获取已有属性与属性值接口
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from "@/api/product/attr";
// 获取分类的仓库
import useCategoryStore from "@/store/modules/category";
import type {
  AttrResponseData,
  Attr,
  AttrValue,
} from "@/api/product/attr/type";
import { ElMessage } from "element-plus";
let categoryStore = useCategoryStore();
// 存储已有的属性与属性值
let attrArrDate = ref<Attr[]>([]);
// 定义card组件内容切换变量
let scene = ref<boolean>(true);
// 准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([]);
// 判断数据是否全部请求完毕
let loading = ref<boolean>(false);
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: "", // 新增属性名字
  attrValueList: [],
  categoryId: null, // 三级分类ID
  categoryLevel: 3, // 代表三级分类
});
watch(
  () => categoryStore.c3Id,
  async () => {
    // 清空上一次查询的属性与属性值
    attrArrDate.value = [];
    //  保证三级分类得有才能发请求
    if (!categoryStore.c3Id) return;
    getAttr();
  },
);
// 获取已有的属性与属性值方法
const getAttr = async () => {
  loading.value = true;
  const { c1Id, c2Id, c3Id } = categoryStore;
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  if (result.code === 200) attrArrDate.value = result.data;
  loading.value = false;
};
// 添加属性按钮
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryStore.c3Id, // 点击按钮的时候新增属性的三级分类ID
    categoryLevel: 3,
    id: "",
  });
  // card组件内容切换
  scene.value = false;
};
// 修改属性按钮
const updateAttr = (row: Attr) => {
  loading.value = true;
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)));
  scene.value = false;
  loading.value = false;
};
// 取消按钮
const cancel = () => {
  scene.value = true;
};
// 添加属性值按钮
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true, // 控制每一个属性编辑模式与切换模式的切换
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};
// 保存按钮
const save = async () => {
  let result = await reqAddOrUpdateAttr(attrParams);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    getAttr();
    scene.value = true;
  } else {
    ElMessage({
      type: "error",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};

// 属性值表单元素失去焦点事件
const toLook = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() === "") {
    // 删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能为空!",
    });
    return;
  }
  let repeat = attrParams.attrValueList.find((item) => {
    if (item !== row) {
      return item.valueName === row.valueName;
    }
  });
  if (repeat) {
    // 讲重复的属性值删除
    attrParams.attrValueList.splice($index, 1);
    ElMessage({
      type: "error",
      message: "属性值不能重复!",
    });
    return;
  }

  row.flag = false;
};
// 属性值div点击事件
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true;
  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
// 删除已有的属性方法
const deleteAttr = async (attrId: number) => {
  let result = await reqRemoveAttr(attrId);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};

// 路由组件销毁的时候，把仓库分类相关数据清空
onBeforeUnmount(() => {
  categoryStore.$reset();
});
</script>

<style scoped lang="scss">
.attr_card {
  margin-bottom: 16px;

  .attr_table {
    margin: 16px 0;

    .attr_table-tag {
      margin: 0 2px;
    }
  }
}

.attr_button-marginTop {
  margin-top: 16px;
}
</style>
